import { Component, Vue } from 'vue-property-decorator'

import styles from './Result.less'
import { Route } from 'vue-router'
Component.registerHooks(['beforeRouteLeave'])
@Component({})
export default class AuthResult extends Vue {
  private id: string = ''
  private name: string = ''
  private cancel: boolean = false
  private new: boolean = false
  private second: number = 5
  private timer: number = 0
  private from: string = ''
  protected render(h: any) {
    return (
      <div class={styles.successDiv}>
        <i class="el-icon-circle-check" />
        <h3 class={styles.content}>
          {this.cancel ? `取消授权成功` : `授权成功`}
        </h3>
        {this.new && (
          <p class={styles.desc}>
            您可以在授权应用列表中查看新授权的应用
            <br />
            或选择将已授权的印章同步到其他应用
          </p>
        )}
        <p class={styles.opts}>
          {this.new ? (
            <span>
              <el-button type="default" onClick={this.toAuthOther}>
                同步到其他应用
              </el-button>
              <el-button type="primary" onClick={this.back}>
                返回列表
              </el-button>
            </span>
          ) : (
            <el-button type="default" onClick={this.back}>
              {this.second ? `确定（${this.second}s）` : `确定`}
            </el-button>
          )}
        </p>
      </div>
    )
  }

  mounted() {
    this.id = (this.$route.query.id as string) || ''
    this.name = (this.$route.query.name as string) || ''
    this.cancel = !!(this.$route.query.cancel as string) || false
    this.new = !!(this.$route.query.new as string) || false
    this.from = (this.$route.query.from as string) || ''
    if (!this.new) {
      // 倒计时
      clearInterval(this.timer)
      this.second = 5
      this.timer = setInterval(() => {
        if (this.second === 0) {
          clearInterval(this.timer)
          // this.second = 3
          this.back()
        } else {
          this.second--
        }
      }, 1000)
    }
  }

  toAuthOther() {
    this.$router.push({
      name: 'authorizeOthers',
      query: { id: this.id, name: this.name },
    })
  }

  back() {
    if (this.from) {
      this.$router.push({ name: this.from })
    } else {
      this.$router.push({ name: 'authorizeApp', params: { type: 'cloud' } })
    }
  }

  beforeRouteLeave(to: Route, from: Route, next: any) {
    this.timer && clearInterval(this.timer)
    next()
  }
}
